package org.lisen.oauth2example.authorizationserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.lisen.oauth2example.authorizationserver.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/authServer")
@Slf4j
public class AuthController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/token")
    public HttpEntity getAccessToken(HttpServletRequest request) throws OAuthProblemException, OAuthSystemException {

        log.info("认证服务器，接收到客户的令牌请求 .... ");

        OAuthTokenRequest tokenReq = new OAuthTokenRequest(request);
        String clientSecret = tokenReq.getClientSecret();

        String code = tokenReq.getCode();
        Boolean codeExist = stringRedisTemplate.hasKey(code);

        if(clientSecret != null && !"".equals(clientSecret) && codeExist) {
            /*OAuthIssuerImpl oAuthIssuer = new OAuthIssuerImpl(new MD5Generator());
            String token = oAuthIssuer.accessToken();*/

            Map<String,Object> claims = new HashMap<>();
            claims.put("name","zs");
            claims.put("phone","13875109876");
            String token = JwtUtils.createJwt(claims, 1000 * 60 * 60 * 24);

            log.info("token = " + token);

            //构造保护令牌的响应对象
            OAuthResponse oAuthResponse = OAuthASResponse
                    .tokenResponse(HttpServletResponse.SC_OK)
                    .setAccessToken(token)
                    .buildJSONMessage();

            return new ResponseEntity(oAuthResponse.getBody(), HttpStatus.valueOf(oAuthResponse.getResponseStatus()));
        }

        return null;
    }

}